package jgl.vajra.kingkong.widget.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatImageView;

public class RoundImageView extends AppCompatImageView {
    public RoundImageView(Context context) {
        super(context);
        setWillNotDraw(false);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setWillNotDraw(false);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (getDrawable() == null) return;
        Bitmap bit = ((BitmapDrawable) getDrawable()).getBitmap();
        //绘制圆圈
        Bitmap oval = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.RGB_565);
        Canvas canvasOval = new Canvas(oval);
        RectF rectF = new RectF();
        rectF.set(0, 0, getWidth(), getHeight());
        Paint tempPaint = new Paint();
        tempPaint.setAntiAlias(true);
        canvasOval.drawOval(rectF, tempPaint);
        //绘制底图
        Bitmap bg = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.RGB_565);
        Canvas canvasBg = new Canvas(bg);
        canvasBg.drawBitmap(bit, 0, 0, null);
        Drawable shadow = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{Color.TRANSPARENT, Color.TRANSPARENT, Color.GRAY});
        shadow.setBounds(0, 0, getWidth(), getHeight());
        shadow.draw(canvasBg);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        canvasBg.drawBitmap(oval, 0, 0, paint);
        canvas.drawBitmap(bg, 0, 0, null);


    }

}
